import asyncio
import datetime
import logging

from aiogram import Bot, Dispatcher, executor, types

from api import Database, format_message

API_TOKEN = os.environ['TOKEN']
intervals = [1, 5, 14, 35]  # Сейчас это минуты, но вообще это дни, но для демонстрации поменяю
# Configure logging
logging.basicConfig(level=logging.INFO)

# Initialize bot and dispatcher
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
db = Database("users.db")


@dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message):
    user_id = message.from_user.id
    if db.is_user_exist(user_id):
        await message.reply("Welcome back!")
    else:
        await message.reply(
            "Hi, new User!\nI'm remember_bot\nYou can add new words to remember\n/add_word {text}\nAlso you can see your words with\n/show\nAlso you can delete word with\n/delete {text}\nYou can delete all words with\n/clear")


@dp.message_handler(commands=['add_word'])
async def add_word(message: types.Message):
    text = message.text.replace("/add_word ", "")
    user_id = message.from_user.id
    db.save_word(user_id, text)


@dp.message_handler(commands=['delete'])
async def delete_word(message: types.Message):
    text = message.text.replace("/delete ", "")
    user_id = message.from_user.id
    db.delete_word_from_user(user_id, text)
    await message.answer('The word was deleted!')


@dp.message_handler(commands=['show'])
async def show(message: types.Message):
    user_id = message.from_user.id
    if db.is_user_exist(user_id):
        msg = ""
        for i in db.get_user(user_id):
            msg += "{} -> the next repeat is in {} minutes".format(i[2], intervals[i[4]])
        await message.answer("Your words:\n" + msg)
    else:
        await message.answer("Sorry! You have not words!")


@dp.message_handler(commands=['clear'])
async def clear(message: types.Message):
    user_id = message.from_user.id
    db.clear(user_id)
    await message.answer("All records was cleared")


async def notify_loop(_dp: Dispatcher):
    users = db.get_all_users()
    for j in users.keys():
        words = []
        for i in users[j]:
            date = datetime.datetime.fromisoformat(i[3])
            now = datetime.datetime.now()
            counter = i[4]
            minutes_left = (now - date).seconds // 60
            if minutes_left >= sum(intervals[:counter+1]):
                logging.log(logging.INFO, "{}, {}, {}".format(i[1], minutes_left, "Need to remember!"))
                words.append([i[2]])
                db.update_word_counter(i[0], counter + 1)
            if counter + 1 >= len(intervals):
                db.delete_word_by_id(i[0])
        if len(words) != 0:
            await _dp.bot.send_message(j, format_message(words))


async def task_loop(_dp: Dispatcher):
    while True:
        asyncio.create_task(notify_loop(_dp))
        await asyncio.sleep(20)


async def on_startup(_dp: Dispatcher):
    asyncio.create_task(task_loop(_dp))


if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
